// import JSZip from 'jszip'
// import FileSaver from 'file-saver'
import axios from 'axios'
import { ItMessage } from '@/components'

/**
 * 文件处理
 */

// 归类的文件类型
const fileTypes = [
  'word',
  'excel',
  'ppt',
  'pdf',
  'image',
  'gif',
  'video',
  'zip',
]

// 支持的文件格式 每组二维数组元素对应一种文件类型，例如：['doc', 'docx'] 对应 'word'
const fileFormatCollections = [
  ['doc', 'docx'],
  ['xls', 'xlsx'],
  ['ppt', 'pptx'],
  ['pdf'],
  ['jpg', 'jpeg', 'png', 'bmp'],
  ['gif'],
  ['mp4', 'mp3'],
  ['zip', 'rar', '7z'],
]
const fileFormatMap = {
  projectVerify: [
    'doc',
    'docx',
    'xls',
    'xlsx',
    'ppt',
    'pptx',
    'pdf',
    'jpg',
    'jpeg',
    'gif',
    'png',
    'bmp',
    'mp4',
    'mp3',
  ],
}

export function FileHandle() {
  // 校验文件格式
  const getAcceptFileFormats = (key) =>
    fileFormatMap[key].map((format) => `.${format}`).join(',')

  // 文件下载
  const downloadFile = async (url, name) => {
    if (!name) {
      let { fileName } = parseFileUrl(url)
      name = fileName
    }
    FileSaver.saveAs(url, name)
  }

  // 批量压缩下载
  /**
   *
   * @param {Array} fileTable 文件路径数组
   * @param {String} fileTableTitle 文件zip名称
   */
  function getFile(url) {
    return new Promise((resolve, reject) => {
      axios({
        method: 'get',
        url,
        responseType: 'blob',
      })
        .then((data) => {
          resolve(data.data)
        })
        .catch((error) => {
          reject(error.toString())
        })
    })
  }
  function handleBatchDownload(fileTable, filename) {
    const dataUrl = []
    for (let file of fileTable) {
      dataUrl.push(file.url) // 把所有要打包文件的url放进数组
    }
    const zip = new JSZip() // 创建一个JSZip实例
    const cache = {}
    const promises = []
    dataUrl.forEach((item) => {
      const promise = getFile(item).then((data) => {
        const arr_name = item.split('/') // stringObject.split 将字符串分割成字符串数组
        const file_name = arr_name[arr_name.length - 1] // 获取文件名（数组最后一项）
        zip.file(file_name, data, { binary: true }) // 逐个添加文件
        cache[file_name] = data
      })
      promises.push(promise)
    })
    Promise.all(promises).then(() => {
      zip.generateAsync({ type: 'blob' }).then((content) => {
        downloadFile(content, filename + '.zip')
      })
    })
  }
  // 判断上传文件类型是否在范围
  const applyArr = (arr, file) => {
    return new Promise((resolve, reject) => {
      //二维数组转一维数组
      let newArr = [].concat.apply([], arr)
      //文件类型
      let fileType = file.name.split('.')[file.name.split('.').length - 1]
      if (newArr.indexOf(fileType) == -1) {
        ItMessage({ content: '不支持该类型文件上传' })
        reject(false)
      } else {
        resolve(true)
      }
    })
  }
  const getExe = (file) => {
    return file.name.includes('.exe')
  }
  // 文件上传 //flag 0 格式不限 1 除exe之外
  const handleUploadFile = async (file, flag) => {
    // await applyArr(fileFormatCollections, file)
    if (flag == 1 && getExe(file)) {
      ItMessage({ content: '不支持该类型文件上传' })
      return false
    } else if (file.name.indexOf(',') != -1) {
      ItMessage({ content: '文件名中不能有","' })
      return false
    } else {
      let res = await fetchFileUpload(file)
      if (res.success) {
        const { fileName, fileType } = parseFileUrl(res.data)
        const fileObj = {
          timeid: new Date().getTime(),
          name: fileName,
          path: res.data,
          type: fileType,
        }
        return fileObj
      } else {
        ItMessage({ content: '不支持该类型文件上传' })
        return false
      }
    }
  }
  // 图片上传
  const fetchPicUpload = async (file) => {
    if (file.name.indexOf(',') != -1) {
      ItMessage({ content: '图片名中不能有逗号' })
      return false
    } else {
      let res = await fetchFileUpload(file)
      const { fileName, fileType } = parseFileUrl(res.data)
      const fileObj = {
        timeid: new Date().getTime(),
        name: fileName,
        path: res.data,
        type: fileType,
      }
      return fileObj
    }
  }

  // 根据链接返回文件名称、类型
  // in: https:/***/xxx.pdf
  // out: { fileName, fileFormat, fileType }
  const parseFileUrl = (fileUrl) => {
    let fileName = fileUrl
    if (fileUrl.includes('/')) {
      const splitedFile = fileUrl.split('/')
      const splitedFileLength = splitedFile.length
      fileName = splitedFile[splitedFileLength - 1]
    }
    const splitedFileName = fileName.split('.')
    const fileFormat = splitedFileName[splitedFileName.length - 1]
    const getFileType = (fileFormat) => {
      const filtedFileIndex = fileFormatCollections
        .map((fileFormats, index) => {
          if (fileFormats.includes(fileFormat)) {
            return index
          }
        })
        .filter((item) => item >= 0)[0]
      return fileTypes[filtedFileIndex]
    }
    const fileType = getFileType(fileFormat)
    return { fileName, fileFormat, fileType }
  }

  // htmlExportExcel
  const htmlExportExcel = ({ html, name, style = '' }) => {
    const stylecss = `
    table{
      border: none;
    }
    table td {
      font-size: 12px;
      min-height: 30px;
      text-align: center;
      color: #000;
      mso-number-format:"@";
    }
    .textLeft {
      text-align: left;
    }
    table td.tishi{
      text-align: left;
      font-size: 10px;
      border: none;
      height: 20px;
    }
    .tablehead{
      font-size: 20px;
    } ${style}
    `
    const base64 = (s) => {
      return window.btoa(unescape(encodeURIComponent(s)))
    }

    const uri = 'data:application/vnd.ms-excel;base64,'
    let template = `
  <html xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40">
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
      <head><style type="text/css"> ${stylecss}</style></head>
      <body><table class="excelTable" cellspacing="0" cellpadding="0" border="1" >${html}</table><body></html>`
    downloadFile(uri + base64(template), `${name || '数据'}.xls`)
  }

  // jsonToDoc

  const htmlExportWord = ({ html, name }) => {
    const base64 = (s) => {
      return window.btoa(unescape(encodeURIComponent(s)))
    }
    let styles = `
    h1{
      text-align: center;
    }
    h2,p{
      text-indent:2em
    }
    table td {
      font-size: 16px;
      min-height: 30px;
      text-align: center;
      color: #000;
      mso-number-format:"@";
    }
    table{
      border-collapse: collapse;
      border-spacing: 0;
    }
    td,th {
      padding: 0;
    }
    .pure-table td,.pure-table th {
      border-left: 1px solid #000;
      border-width: 0 0 0 1px;
      font-size: inherit;
      margin: 0;
      overflow: visible;
      padding: .5em 1em;
  }
    .pure-table thead {
      color: #000;
      text-align: left;
      vertical-align: bottom;
      border-top: 1px solid #000;
    }
    .pure-table th{
      border-top: 1px solid #000;
    }
    .pure-table tr th,
    .pure-table tr td{
      border-right: 1px solid #000;
    }
    .pure-table td , .pure-table th{
      background-color: transparent;
      border-bottom: 1px solid #000;
    }

    .pure-table tbody>tr:last-child>td {
      border-bottom-width: 0;
    }
   `
    const uri = 'data:application/msword;base64,'
    let template = `
  <html xmlns:o="urn:schemas-microsoft-com:office:office"
  xmlns:x="urn:schemas-microsoft-com:office:word" xmlns="http://www.w3.org/TR/REC-html40">
      <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"/>
      <head><style type="text/css">${styles}</style></head>
      <body>${html}<body></html>`

    return uri + base64(template)
  }

  const jsonToHtml = (data, excelList) => {
    // const mapList = {
    //   order: '序号',
    //   title: '诉求标题',
    // }
    const dataList = data.map((item, index) => {
      return {
        order: index + 1,
        ...item,
      }
    })
    const keyList = Object.keys(excelList)
    const htmlHead = `<thead><tr>${keyList
      .map((item) => `<td class="tablehead">${excelList[item]}</td>`)
      .join('')}</tr></thead>`

    const htmlBody = dataList
      .map((item) => {
        return `<tr>${keyList
          .map((key) => `<td>${item[key]}</td>`)
          .join('')} </tr>`
      })
      .join('')
    return `${htmlHead}${htmlBody}`
  }

  return {
    getAcceptFileFormats,
    parseFileUrl, // 根据链接返回文件名称、类型
    htmlExportExcel, // 导出为excel
    handleUploadFile, // 上传文件
    handleBatchDownload, // 批量压缩下载
    downloadFile, // 文件下载
    fetchPicUpload, //上传图片
    jsonToHtml,
    htmlExportWord,
  }
}
